from fastapi import FastAPI, Request, Form, File, UploadFile
from typing import List

# -*- coding: utf-8 -*-
import os
import numpy as np
from calibration import calib,dedistortion
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import time

#取消科学计数法
np.set_printoptions(suppress=True)


app = FastAPI()

@app.get("/")
def home(request: Request):
    return "fastapi"


@app.post("/")
async def detect_via_web_form(request: Request,
							file_list: List[UploadFile] = File(...),
                            width:int =Form(0),
                            height:int =Form(0),
							img_size: float = Form(640)):

    
     # 创建文件夹    
    t = time.time()
    ticks = str(int(round(t * 1000000)))
    img_dir = "data/tmp/"+ticks
    img_save_dir = "data/save/"+ticks
    if(not os.path.exists(img_dir)):
        os.makedirs(img_dir)
    if(not os.path.exists(img_save_dir)):
        os.makedirs(img_save_dir)
    img_type = "jpg"
    
    img_batch = []
    for i, file in enumerate(file_list):
        img = Image.open(BytesIO(await file.read()))
        img.filename = f'image{i}.jpg'
        img_batch.append(img)
        imgpath =  os.path.join(img_dir, img.filename) 
        img.save(imgpath)
    
    inter_corner_shape = (width, height)
    size_per_grid = img_size  #方格尺寸 长度单位 米 此处表示20mm = 0.020
    
    # calibrate the camera
    mat_inter, coff_dis = calib(inter_corner_shape, size_per_grid, img_dir, img_type)
    # dedistort and save the dedistortion result.
    dedistortion(inter_corner_shape, img_dir, img_type, img_save_dir, mat_inter, coff_dis) #矫正图形并保存

    res= {}
    res["mat_inter"]= mat_inter.tolist()
    res["coff_dis"]= coff_dis.tolist()
    return res #json.dumps(res)


class CarlibreateModel:
    code=200
    msg="成功"
    mat_inter =[]
    coff_dis =[]

if __name__ == '__main__':
	import uvicorn
	app_str = 'server:app'
	uvicorn.run(app_str, host='0.0.0.0', port=8000, reload=True, workers=1)
